# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
mailer  = require 'nodemailer'
pgsql   = require 'pg'
crypto  = require 'crypto'
moment  = require 'moment'

# 发送电子邮件
# params 是一个 object，可以包含下列的 key:
#   subject: 邮件主题
#   to: 收件地址
#   cc: 抄送地址
#   html: HTML 格式正文
#   text: 文本格式正文
#
sendmail = (params) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    return done(client) and console.log(err) if err

    await client.query "select * from web_email limit 1", defer err, result
    return done(client) and console.log(err) if err
    done()

    if result.rows.length == 0
        return console.error '邮件服务未配置，不能发送电子邮件'

    record = result.rows[0]

    secure_key = Buffer.from settings.secure_key, 'hex'
    if secure_key.length isnt 16
        return console.error '安全密钥配置错误，必须由 32 位[0-9A-F]数字组成'

    decipher = crypto.createDecipheriv 'des-ede', secure_key, new Buffer('')
    passwd = decipher.update record.smtp_passwd, 'hex', 'utf8'
    passwd += decipher.final 'utf8'

    config =
        logger: false,
        debug: false,
        host: record.smtp_host,
        port: record.smtp_port,
        secure: record.smtp_ssl,
        tls: {
            rejectUnauthorized: false
        }
        auth: {
            user: record.smtp_from,
            pass: passwd,
        }
    mail =
        subject: params.subject or '无主题',
        from: "\"#{record.smtp_name}\" #{record.smtp_from}",
        bcc: "x@lucky-byte.com",
        to: params.to,
        cc: params.cc,
        html: params.html,
        text: params.text,

    transporter = mailer.createTransport config
    transporter.sendMail mail

module.exports = sendmail
